<template>
  <el-dialog append-to-body :visible.sync="visible" :title="id ? '编辑群组' : '新建群组'">
    <div>
      <el-form label-width="60px" size="mini">
        <el-form-item label="名称">
          <el-input v-model="formData.name" placeholder="请输入群组名称" />
        </el-form-item>
        <el-form-item label="成员">
          <FormItemView :selecting="selecting" :value="userNames" @click="handleOpen" />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="handleClose">
        取消
      </el-button>
      <el-button size="mini" type="primary" @click="handleOk">
        保存
      </el-button>
    </div>
    <staff-template-input ref="StaffTemplateInputRef" :type="[1]" title="选择人员" @close="selecting = false" />
  </el-dialog>
</template>

<script>
import { groupGet, groupAdd, groupUpdate } from '@/api/group'
import FormItemView from '@/components/FormItemView'
import StaffTemplateInput from '@/containers/StaffTemplate/template'
export default {
  name: '',
  components: { FormItemView, StaffTemplateInput },
  data() {
    return {
      visible: false,
      selecting: false,
      formData: {},
      id: null
    }
  },
  computed: {
    userNames: function() {
      if (!this.$data.formData.userIdList) {
        return ''
      }
      return '已选' + this.$data.formData.userIdList.length + '人'
    }
  },
  methods: {
    open(id) {
      this.$data.visible = true
      this.$data.id = id

      id && this.postGroupGet(id)
      return new Promise((resolve, reject) => {
        this.monitor = { resolve, reject }
      })
    },
    postGroupGet(id) {
      groupGet({ id }).then(res => {
        this.$data.formData = res
      })
    },
    postGroupSubmit() {
      let post = null
      const data = this.$data.formData
      data.userIds = data.userIdList
      if (this.$data.id) {
        post = groupUpdate
        data.id = this.$data.id
      } else {
        post = groupAdd
      }

      return post(data)
    },
    handleOpen() {
      let orgList = []
      if (this.$data.formData.userIdList) {
        orgList = this.$data.formData.userIdList.map(e => e + '')
      }

      this.$refs.StaffTemplateInputRef.open({ orgList }).then(res => {
        const userIdList = res.orgList.map(e => e.id)
        this.$set(this.$data.formData, 'userIdList', userIdList)
      })
    },
    handleClose() {
      this.$emit('close')
      this.$data.visible = false
    },
    handleOk() {
      this.postGroupSubmit().then(() => {
        this.$data.visible = false
        this.monitor.resolve()
        this.$message.success('保存成功')
      })
    }
  }
}
</script>

<style>

</style>
